<template>
  <div>
    <el-row>
      <el-col :span="12">
        <cs-cell label="用户列表">
          <!--          <el-scrollbar style="height: 500px">-->
          <avue-crud :option="userOption"
                     :data="userListData"
                     :table-loading="loading"
                     :page="pageUser"
                     :permission="userListPermissionList"
                     ref="crud"
                     @row-click="handleRowClick"
                     @selection-change="selectionChange"
                     @select="handleRowSelect"
                     @current-change="currentChange"
                     @size-change="sizeChange"
                     @row-del="deleteUser"
                     @on-load="onloadUser">
            <template slot="status" slot-scope="scope">
              <el-select id="id-business-components-offershareelnsinde-status"
                         :disabled="openCheck || scope.row.status == 2" v-model="scope.row.status" size="mini"
                         @change="statusChange($event,scope.row)">
                <el-option v-for="item in statusList" :key="item.dictKey"
                           v-if="(scope.row.status == 2 && item.dictKey == 2) || (scope.row.status != 2 && item.dictKey != 2)"
                           :label="item.dictValue" :value="item.dictKey*1">
                </el-option>
              </el-select>
            </template>
            <template slot="permission" slot-scope="scope">
              <el-select id="id-business-components-offershareelnsinde-permission"
                         multiple :disabled="openCheck || scope.row.status == 2" v-model="scope.row.permission"
                         size="mini"
                         @change="permissionChange($event,scope.row)">
                <el-option v-for="item in permissionList" :key="item.dictKey"
                           :label="item.dictValue" :value="item.dictKey">
                </el-option>
              </el-select>
            </template>
            <template slot="menuRight">
              <el-link v-if="!openCheck" :disabled="offerId === ''"
                       id="id-business-components-offershareelnsinde-handleUserAdd" type="primary"
                       @click="handleUserAdd">新增用户
              </el-link>
            </template>
            <template slot="menu" slot-scope="{row}">
              <!--<el-button-->
              <!--  id="id-business-components-offershaare-deleteAccount"-->
              <!--  :disabled="row.id == null"-->
              <!--  type="primary"-->
              <!--  size="mini"-->
              <!--  icon="el-icon-delete"-->
              <!--  @click="deleteUser(row)"-->
              <!--&gt;删除-->
              <!--</el-button>-->
            </template>
          </avue-crud>
          <!--          </el-scrollbar>-->
        </cs-cell>
      </el-col>
      <el-col :span="12">
        <cs-cell label="账户列表">
          <!--          <el-scrollbar style="height: 500px">-->
          <avue-crud :option="accountOption"
                     :data="accountListData"
                     :table-loading="accountloading"
                     ref="crudAccount"
                     @on-load="onloadAccount"
                     @row-del="deleteAccount"
                     :permission="userAccountListPermissionList"
          >
            <template slot="permission" slot-scope="scope">
              <el-select id="id-business-components-offershareelnsinde-permission-two"
                         multiple collapse-tags :disabled="openCheck" v-model="scope.row.permission" size="mini"
                         v-if="scope.row.id != null && scope.row.id != -1"
                         @change="accountPermissionChange($event,scope.row)">
                <el-option v-for="item in permissionOptions" :key="item.value"
                           :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </template>
            <template slot="menuRight">
              <el-link v-if="!openCheck" :disabled="userId === '' || !enableAddAccount"
                       id="id-business-components-offershareelnsinde-handleAccountAdd" type="primary"
                       @click="handleAccountAdd">新增账户
              </el-link>
            </template>
            <!--<template slot="menu" slot-scope="{row}">-->
            <!--  <el-button-->
            <!--    id="id-business-components-offershaare-deleteAccount"-->
            <!--    :disabled="row.id == null"-->
            <!--    type="primary"-->
            <!--    size="mini"-->
            <!--    icon="el-icon-delete"-->
            <!--    @click="deleteAccount(row)"-->
            <!--  >删除-->
            <!--  </el-button>-->
            <!--</template>-->
          </avue-crud>
          <!--          </el-scrollbar>-->
        </cs-cell>
      </el-col>
    </el-row>
    <!--    user新增dialog-->
    <el-dialog :visible.sync="userAddDialog" :modal-append-to-body="false" width="80%" :append-to-body="true"
               :before-close="userDialogClose">
      <offer-share-user-add ref="userAdd"></offer-share-user-add>
      <span slot="footer" class="dialog-footer">
        <el-button id="id-business-components-offershareelnsinde-userDialogClose"
                   @click="userDialogClose">取 消</el-button>
        <el-button id="id-business-components-offershareelnsinde-submitUser" type="primary"
                   @click="submitUser">提 交</el-button>
      </span>
    </el-dialog>
    <!--    account新增dialog-->
    <el-dialog :visible.sync="accountAddDialog" :modal-append-to-body="false" width="80%" :append-to-body="true"
               :before-close="accountAddDialogClose">
      <offer-share-account-add ref="accountAdd" :targetUserId="userId"
                               :exclude-platform-ids="excludePlatformIds"></offer-share-account-add>
      <span slot="footer" class="dialog-footer">
        <el-button id="id-business-components-offershareelnsinde-accountAddDialogClose" @click="accountAddDialogClose">取 消</el-button>
        <el-button id="id-business-components-offershareelnsinde-submitAccount" type="primary" @click="submitAccount">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import offerShareAccountAdd from './offerShareAccountAdd'
import offerShareUserAdd from './offerShareUserAdd'
import {getSysDictList} from '@/api/system/dict'
import {
  removeUserOffers,
  getOfferUserList,
  updateUserOffers,
  updateAccountOffers,
  getUserAccountList,
  removeAccountOffers
} from '@/api/business/share'
import CsCell from "@/components/CsCell/CsCell";

export default {
  name: 'offerShareInside',
  components: {
    offerShareAccountAdd, offerShareUserAdd, CsCell
  },
  props: {
    offerId: {
      type: String
    },
    openCheck: {
      type: String | Boolean
    },
  },
  watch: {
    offerId: {
      deep: true,
      handler(val, old) {
        if (val === old) {
          return
        }
        this.offerId = val
        this.onloadUser(this.pageUser, this.query)

        //获取用户权限
        this.getSysDictList()
        // //获取用户状态
        //获取用户状态
        if (this.$refs.accountAdd) {
          this.$refs.accountAdd.$refs.crud.selectClear()
        }
        this.delBtn()
      }
    },
  },
  data() {
    return {
      userOption: {
        highlightCurrentRow: true,
        editBtn: false,
        addBtn: false,
        refreshBtn: false,
        columnBtn: false,
        menuWidth: 80,
        // selection: true,
        tip: false,
        menu: true,
        height: 300,
        column: [
          {
            label: '用户名称',
            prop: 'userName',
            width: 100,
          },
          // {
          //   label: '状态',
          //   prop: 'status',
          //   slot: true,
          //   width: 100,
          // },
          {
            label: '身份',
            prop: 'roleName',
          }, {
            label: '权限',
            prop: 'permission',
            slot: true,
          },
        ]
      },
      userListData: [],//用户数据
      pageUser: {
        pageSize: 10,
        layout: "total,pager,prev, next",
        currentPage: 1,
        total: 0
      },
      statusList: [],
      permissionList: [],//权限列表
      //账户列表配置
      enableAddAccount: false,
      excludePlatformIds: [],
      accountOption: {
        editBtn: false,
        addBtn: false,
        refreshBtn: false,
        columnBtn: false,
        menuWidth: 80,
        height: 300,
        menu: true,
        column: [
          {
            label: '账户名称',
            prop: 'accountName',
            width: 100,
          }, {
            label: '权限',
            prop: 'permission',
            slot: true,
          }, {
            label: '账户ID',
            prop: 'platformId',
          }
        ]
      },
      accountListData: [],//账户数据
      accountloading: false,
      loading: true,
      userId: '',
      userAddOfferId: '',
      query: {},//搜索数据
      accountPermissionList: [],//账户列表权限
      userAddDialog: false,//user新增弹窗
      accountAddDialog: false,//account新增弹窗
      pageAccount: {
        pageSize: 10,
        layout: "total,pager,prev,next",
        currentPage: 1,
        total: 0
      },
      // 分享权限列表
      permissionOptions: [{
        value: '1',
        label: '含花费'
      }, {
        value: '2',
        label: '含点击'
      }, {
        value: '3',
        label: '含曝光'
      }, {
        value: '4',
        label: '含安装'
      }]
    }
  },
  created() {
    this.getSysDictList()
  },
  methods: {
    //获取用户权限
    getSysDictList() {
      getSysDictList("user_offer_data_permission,user_offer_status,account_offer_permission").then(map => {
        this.permissionList = map['user_offer_data_permission'];
        this.statusList = [...map['user_offer_status']];
        this.statusList.push({dictKey: '2', dictValue: '创建者'});
        this.accountPermissionList = map['account_offer_permission'];
      })
    },
    userAccountListPermissionList(key, row) {
      if (key === 'delBtn') {
        return (row.id != null && row.id != -1);
      }
      return true;
    },
    userListPermissionList(key, row) {
      if (key === 'delBtn') {
        return (row.status != 2);
      }
      return true;
    },
    /**
     * 修改菜單是否顯示
     */
    delBtn() {
      if (!this.openCheck) {
        this.userOption.menu = true
        this.accountOption.menu = true
      }
    },
    //userTable点击
    handleRowClick(row,column, event) {
      this.userId = row.userId
      let Id = {
        userId: this.userId
      }
      console.log('点击1', event)
      this.enableAddAccount = (row.status != 2);
      this.onloadAccount(this.pageAccount, Id, () => {
        // this.$refs.crud.toggleRowSelection(row, true)
      });
    },
    handleRowSelect(selection, row) {
      // console.log('点击3')
      // this.userId = row.userId
      // let Id = {
      //   userId: this.userId
      // }
      // this.onloadAccount(this.pageAccount, Id, () => {
      //   this.$refs.crud.toggleRowSelection(row, true)
      // });
    },
    selectionChange(list) {
      // console.log('点击2')
      // this.selectionList = list;
    },
    currentChange(currentPage) {
      this.pageUser.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.pageUser.pageSize = pageSize;
    },
    //user列表点击删除
    deleteUser(row) {
      removeUserOffers(row.id).then(res => {
        if (res)
          this.$message({type: 'success', message: '删除成功'})
        this.onloadUser(this.pageUser)
      })
    },
    selectionClear() {
      this.$nextTick(() => {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      })
    },
    //获取user列表
    onloadUser(page, params = {}) {
      this.loading = true
      if (!this.offerId) {
        this.loading = false;
        this.pageUser.total = 0;
        this.userListData = [];
        return
      }
      getOfferUserList(
        page.currentPage,
        page.pageSize,
        // Object.assign(params, this.query, {isShare: !this.openCheck})
        {
          offerId: this.offerId,
          isShare: !this.openCheck
        }
      ).then(res => {
        const data = res.data.data
        this.pageUser.total = data.total;
        data.records.map(item => {
          if (item.permission === '0') return item.permission = []
          item.permission = item.permission.split(',')
          if (item.permission[0] === '') {
            item.permission = []
          }
        })
        // if (data.records.length > 0) {
        //   this.handleRowClick(data.records[0])
        //   this.userId = data.records[0].userId
        // }
        this.userListData = data.records;
        this.loading = false;
        this.selectionClear();
      })
    },
    //修改状态
    statusChange(event, row) {
      updateUserOffers({id: row.id, status: event}).then(res => {
        if (res.data.code === 200) {
          this.$message({
            type: 'success',
            message: '状态修改成功!'
          })
        }
      })
    },
    //修改权限
    permissionChange(event, row) {
      updateUserOffers({id: row.id, permission: event.join(',')})
    },
    //修改账户列表权限
    accountPermissionChange(event, row) {
      updateAccountOffers({id: row.id, permission: event.join(',')})
    },
    // user新增
    handleUserAdd() {
      this.userAddDialog = true
      this.$nextTick(() => {
        this.$refs.userAdd.onLoad(this.$refs.userAdd.page)
      })
      // this.$refs.userAdd.handleClearSelection();
    },
    onloadAccount(page, params = {}, callback) {
      if (!this.userId) return;
      this.accountloading = true
      if (!this.offerId) {
        this.accountloading = false;
        this.pageAccount.total = 0;
        this.accountListData = [];
        return
      }
      getUserAccountList(
        page.currentPage,
        page.pageSize,
        {
          userId:this.userId,
          offerId:this.offerId
        }
      ).then(res => {
        const data = res.data.data
        //this.pageAccount.total = data.total;
        data.records.map(item => {
          let permission = item.permission + ''
          item.permission = permission.split(',')
        })
        this.accountListData = data.records;
        this.accountloading = false;
        this.selectionClear();
        this.$nextTick(() => {
          // callback()
        })
      })
    },
    //account列表点击删除
    deleteAccount(row) {
      removeAccountOffers(row.id).then(res => {
        if (res)
          this.$message({type: 'success', message: '删除成功'})
        let Id = {
          userId: this.userId
        }
        this.onloadAccount(this.pageAccount, Id)
      })
    },
    // account新增
    handleAccountAdd() {
      this.excludePlatformIds = [];
      this.accountListData.forEach(row => {
        this.excludePlatformIds.push(row.platformId);
      });
      this.accountAddDialog = true
      this.$refs.accountAdd.onLoad(this.$refs.accountAdd.page)
    },
    //用户页面关闭
    userDialogClose() {
      this.userAddDialog = false
      this.$refs.userAdd.$refs.crud.searchReset();
    },
    //账户页面关闭
    accountAddDialogClose() {
      this.accountAddDialog = false
      this.$refs.accountAdd.$refs.crud.searchReset();
    },
    //user提交
    submitUser() {
      if (this.$refs.userAdd.submitAdd()) {
        this.userDialogClose()
      }
    },
    submitAccount() {
      this.$refs.accountAdd.submitAccountAdd()
      this.accountAddDialogClose()
    },

  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-select__tags-text {
  display: inline-block;
  max-width: 70px;
  overflow: hidden; //溢出隐藏
  white-space: nowrap; //禁止换行
  text-overflow: ellipsis; //...
}

::v-deep .el-select {
  .el-tag__close.el-icon-close {
    top: -5px;
    right: -7px;
  }
}
::v-deep .el-table__row{
  cursor: pointer;
}
</style>
